package com.qk.management.web.filter;

import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Objects;

/**
 *
 *
 * @author blusr
 * @version 1.0
 * @date 2025/10/11 10:59
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
@SuppressWarnings("all")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_URI = "/login";
    private static final String TOKEN_NAME = "token";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String requestURI = request.getRequestURI();
        if(Objects.equals(requestURI, LOGIN_URI)){
            chain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(TOKEN_NAME);
        if(Objects.isNull(token)){
            response.setStatus(401);
            return;
        }
        try{
            Claims claims = JwtUtils.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("username: {}", username);
            Object id = claims.get("userid");
            log.info("userid: {}", id);
            chain.doFilter(request, response);
            return;
        }catch (Exception e){
            response.setStatus(401);
            return;
        }
    }
}
